import time
import serial
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
class GetPort:
    def __init__(self):
        self.name = None
    def getCOMPort(self,COM):
        if (len(ports)) == 0:
            print("未找到可用的串口")
            return None
        else:
            for port in ports:
                if COM in port.description:
                    name = port.device
                    print(name)
                    ser = serial.Serial(name, 9600, timeout=1)
                    hex_data = bytes.fromhex('41 71 43')
                    ser.write(hex_data)
                    info = ser.read(50).decode("utf-8")
                    if 'sure' not in info:
                        continue
                    ser.close()
                    return name

    def sendCMD(self,COM, port, cmd):
        # print(self)
        ser = serial.Serial(COM, port)
        hex_data = bytes.fromhex(cmd)
        ser.write(hex_data)
        ser.close()

    def jtag_port(self,comName ,jtag):
        if jtag == 1:
            self.sendCMD(comName, 9600, '41 71 43')
            # print("034cdd")
        if jtag == 2:
            self.sendCMD(comName, 9600, '41 72 43')
        if jtag == 3:
            self.sendCMD(comName, 9600, '41 73 43')
        if jtag == 4:
            self.sendCMD(comName, 9600, '41 74 43')
        if jtag == 5:
            self.sendCMD(comName, 9600, '41 75 43')
        if jtag == 6:
            self.sendCMD(comName, 9600, '41 76 43')
        if jtag == 7:
            self.sendCMD(comName, 9600, '41 77 43')
        if jtag == 8:
            self.sendCMD(comName, 9600, '41 78 43')
        if jtag == 9:
            self.sendCMD(comName, 9600, '41 79 43')

if __name__ == "__main__":
    app = GetPort()